package br.com.abelha.manager.db;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import br.com.abelha.manager.entity.User;

/**
 * @author dalsonsouza
 */

public class DAOUser {
	
	private DBAdapter dbAdapter;
	
	public DAOUser(Context context) {
		dbAdapter = new DBAdapter(context).open();
	}
	
	public User login(String userLogin, String userPassword) {
		String[] columns = new String[]{User.ID,User.USUARIO,User.NOME_COMPLETO, User.PERFIL};
		String[] selectionArgs = new String[]{userLogin,userPassword};
		User user = new User();
		Cursor cursor = dbAdapter.query(user.getTableName(), 
						columns , 
						User.USUARIO + "=? and " + User.SENHA + "=?", 
						selectionArgs, 
						null, 
						null);
		
		if(cursor == null) {
			user = null;
		} else {
			if(cursor.moveToFirst()) {
				int idUser = cursor.getInt(cursor.getColumnIndex(User.ID));
				String nome_completo = cursor.getString(cursor.getColumnIndex(User.NOME_COMPLETO));
				Integer perfil = cursor.getInt(cursor.getColumnIndex(User.PERFIL));
				
				user.setId(idUser);
				user.setUsuario(userLogin);
				user.setNome_completo(nome_completo);
				user.setPerfil(perfil);
			} else {
				user = null;
			}
			
			if(!cursor.isClosed()) cursor.close();
		}
		
		return user;
	}
	
	public long insert(User user) throws Throwable {
		long id = 0;
		try {
			dbAdapter.beginTransaction();
			
			Object[] contents = new Object[]
			           			        {User.ID, null,
			           					User.USUARIO, user.getUsuario(),
			           					User.SENHA, user.getSenha(),
			           					User.NOME_COMPLETO, user.getNome_completo(),
			           					User.PERFIL, user.getPerfil()};
			           			
			  id = dbAdapter.insert(user.getTableName(), contents);
			
			dbAdapter.setTransactionSuccessful();
		} catch (Throwable e) {
			Log.e(this.getClass().getName(), "Error", e);
			throw e;
		} finally {
			dbAdapter.endTransaction();
		}
		
		return id;
	}
	
}
